<template>
  <div class="container">
    <mavon-editor
      v-model = 'editorContent'
      ref="md"
      @imgAdd="handleEditorImgAdd"
      @imgDel="handleEditorImgDel"
      @change="handleChange"
      :style="setStyle"
      v-loading="uploadLoading"
    />
    <div style="margin-top: 15px">
      <el-button type="primary" @click="getData">getData</el-button>
      <el-button type="primary" @click="getHtml">getHtml</el-button>
      <el-button type="primary" @click="getThisImgFiles">getThisImgFiles</el-button>
      <el-button type="primary" @click="show1">show md mavon-editor预览</el-button>
      <el-button type="primary" @click="show2">show md macked解析</el-button>
    </div>
    <dialog-md-show-one ref="dialogShowOne"></dialog-md-show-one>
    <dialog-md-show-two ref="dialogShowTwo"></dialog-md-show-two>
  </div>
</template>
<script>
  import dialogShowOne from './mavonShow1.vue'
  import dialogShowTwo from './mavonShow2.vue'
  export default {
    name: 'markdown',
    data () {
      return {
        uploadLoading: false,
        editorContent:'',
        imgFiles: {},
        html: ''
      }
    },
    computed: {
      setStyle() {
        const height = window.screen.availHeight - 300
        return 'height: ' + height + 'px;'
      }
    },
    methods: {
      // 绑定@imgAdd event
      handleEditorImgAdd(pos, $file) {
        this.uploadLoading = true
        const formdata = new FormData()
        formdata.append('image', $file)
        this.imgFiles[pos] = $file
        this.$http.post(this.$http.adornUrl('/upload/image'), formdata,
          {
            headers: {'Content-Type': 'multipart/form-data'}
          }).then(response => {
          const result = response.data
          if (result && result.code === 0) {
            if (result.success){
              this.$refs['md'].$img2Url(pos, result.data)
              this.$message({message: result.msg, type: 'success'})
            } else {
              this.$message({message: result.msg, type: 'error'})
            }
          }
          this.uploadLoading = false
        }).catch(reason => {
          this.$message({message: reason, type: 'error'})
          this.uploadLoading = false
        })
      },
      handleEditorImgDel(pos) {
        delete this.imgFiles[pos];
      },
      handleChange(value, render) {
        this.html = render
      },
      getData() {
        console.log(this.editorContent)
      },
      getHtml() {
        console.log(this.html)
      },
      getThisImgFiles(){
        console.log(this.imgFiles)
      },
      show1() {
        this.$nextTick(() => {
          this.$refs['dialogShowOne'].init(this.editorContent)
        })
      },
      show2() {
        this.$nextTick(() => {
          this.$refs['dialogShowTwo'].init(this.editorContent)
        })
      }
    },
    components: {
      'dialog-md-show-one': dialogShowOne,
      'dialog-md-show-two': dialogShowTwo
    }
  }
</script>
<style>
</style>
